package com.bigfreakindeals.Protocols.SoapHandlers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.content.Intent;
import android.graphics.Bitmap;
import android.sax.*;
import android.util.Log;
import android.util.Xml;

import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Models.ActiveDeal;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Models.UniversityDeals;

public class GetSchoolListHandler {

	// names of the XML tags
	static final String STATUS = "status";

	static final String PARENT = "cities";
	static final String CITY = "item";

	/* individual city items */
	static final String ID = "id";
	static final String NAME = "name";
	static final String MOBIESCHOOLTITLE = "mobile_school_title";
	static final String SLUG = "slug";
	static final String STATE = "state_name";
	static final String COUNTRY = "country_name";
	static final String LAT = "latitude";
	static final String LONG = "longitude";
	static final String ISAPPROVED = "is_approved";

	static final String COLOR_SCHOOL_FONT = "mobileapp_school_font";
	static final String COLOR_SCHOOL_BG = "mobileapp_background";
	static final String COLOR_TABS_BG_NORMAL = "mobileapp_tabs_background";
	static final String COLOR_TABS_BG_SELECTED = "mobileapp_tabs_selected_background";
	static final String COLOR_TABS_TEXT_NORMAL = "mobileapp_tabs_font";
	static final String COLOR_TABS_TEXT_SELECTED = "mobileapp_tabs_selected_font";
	static final String COLOR_TITLE_BARTOP = "title_bar_top_color";
	static final String COLOR_TITLE_BARBOTTOM = "title_bar_bottom_color";

	static final String FACEBOOK_URL = "facebook_url";
	static final String TWITTER_URL = "twitter_url";

	static final String IMG_MASCOT_MAIN = "mascot_img";
	static final String IMG_MASCOT_BEANSAY = "mobileapp_mascot_img";
	static final String IMG_BUTTON = "mobileapp_mascot_button_img";
	static final String IMG_BEANSAY_TEXT = "mobileapp_mascot_beans_text_img";

	static final String ERROR = "error";

	String feedUrl;

	private static final String SOAP_ACTION = "1";
	private static final String METHOD_NAME = "bigfreakindeals";
	private static final String NAMESPACE = "1";

	public GetSchoolListHandler(String feedUrl) {
		this.feedUrl = feedUrl;
		ApplicationEx.getInstance().getSchoolListCompletedStatus = 1;
		parse();
	}

	public void parse() {

		// update UniversityProfile
		List<UniversityDeals> schoolList = new LinkedList<UniversityDeals>();

		try {

			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);

			HttpTransportSE androidHttpTransport = new HttpTransportSE(feedUrl);

			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject response = (SoapObject) envelope.getResponse();

			String status = response.getProperty(STATUS).toString();
			//ApplicationEx.getInstance().myProfile.setAllSchoolList(new ArrayList<UniversityDeals>());

			if (status != null && status.length() > 0) {
				if (status.contentEquals("false")) {
					// error on active deals
					// get error message

					// TODO ERROR HANDLING
					Intent intent = new Intent(Constant.EVENTS_GETSCHOOLLIST_ERROR);
					intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "");
					ApplicationEx.getInstance().sendBroadcast(intent);

					ApplicationEx.getInstance().getSchoolListCompletedStatus = 2;
					return;

				} else {// status = true; active deals exist

					Vector unisersitySet = (Vector) response.getProperty(PARENT);

					UniversityDeals university;

					for (int count = 0; count <= unisersitySet.size() - 1; count++) {

						SoapObject deals = (SoapObject) unisersitySet.get(count);
						university = new UniversityDeals();
						String	schoolName = null;
						if (deals.getProperty(ID) != null && (deals.getProperty(ID).toString()).length() > 0)
							university.setID(deals.getProperty(ID).toString());

						if (deals.getProperty(NAME) != null){
							university.setSchoolName(deals.getProperty(NAME).toString());
						}else 
							schoolName = "";
						
						if (deals.getProperty(MOBIESCHOOLTITLE) != null){
							university.setSchoolTitle(deals.getProperty(MOBIESCHOOLTITLE).toString());
							
						}
						
						if (deals.getProperty(SLUG) != null){
							
							university.setSchoolSlug( deals.getProperty(SLUG).toString());
						}
						
						
						if (deals.getProperty("image_slug") != null) {
							String imglug = deals.getProperty("image_slug").toString();
							if (imglug != null && imglug.length() > 0) {
								university.setImageSlug(imglug);
							}

							
						}
						if (deals.getProperty("image_slug_version") != null) {
							String version = deals.getProperty("image_slug_version").toString();
							if (version != null && version.length() > 0) {
								university.setImageSlugVersion(version);
							}

						}
						
						
						
						if (deals.getProperty(STATE) != null){
							
						String stateName = deals.getProperty(STATE).toString();
						if (stateName != null && stateName.length() > 0)
							university.setStateName(stateName);
						}
						
						
						if (deals.getProperty(COUNTRY) != null){
							
							university.setCountry(deals.getProperty(COUNTRY).toString());
						}
						
						if (deals.getProperty(LAT) != null){
							university.setLatitude( deals.getProperty(LAT).toString());
						}else 
							university.setLatitude("1");
						
						if (deals.getProperty(LONG) != null){
							university.setLongitude(deals.getProperty(LONG).toString());
						}else 
							university.setLongitude("1");
						
						if (deals.getProperty(ISAPPROVED) != null){
							
						String isApproved = deals.getProperty(ISAPPROVED).toString();

						if (isApproved != null && isApproved.length() > 0)
							university.setIsApproved(Integer.parseInt(isApproved));
						}
						
						
						try{	
						if (deals.getProperty(COLOR_SCHOOL_FONT) != null){
							university.color_school_font = Tools.getIntValue(deals.getProperty(COLOR_SCHOOL_FONT).toString());
						}
						}catch (Exception e) {
							// TODO: handle exception
							university.color_school_font = 0;
							
						}
						if (deals.getProperty(COLOR_SCHOOL_BG) != null)
							university.color_school_bg = Tools.getIntValue(deals.getProperty(COLOR_SCHOOL_BG).toString());
						
						if (deals.getProperty(COLOR_TABS_BG_NORMAL) != null)
							university.color_tabBGColorNormal = Tools.getIntValue(deals.getProperty(COLOR_TABS_BG_NORMAL).toString());
						
						if (deals.getProperty(COLOR_TABS_BG_SELECTED) != null)
							university.color_tabFBGColorSelected = Tools.getIntValue(deals.getProperty(COLOR_TABS_BG_SELECTED).toString());
						
						if (deals.getProperty(COLOR_TABS_TEXT_NORMAL) != null)
							university.setColor_tabFontColorNormal(Tools.getIntValue(deals.getProperty(COLOR_TABS_TEXT_NORMAL).toString()));
						
						if (deals.getProperty(COLOR_TABS_TEXT_SELECTED) != null)
							university.setColor_tabFontColorSelected(Tools.getIntValue(deals.getProperty(COLOR_TABS_TEXT_SELECTED).toString()));
						
						if (deals.getProperty(COLOR_TITLE_BARBOTTOM) != null) 
							university.setColor_titleBarBottomColor(Tools.getIntValue(deals.getProperty(COLOR_TITLE_BARBOTTOM).toString()));
						
						if (deals.getProperty(COLOR_TITLE_BARTOP) != null) {
						
							
							university.setColor_titleBarTopColor(Tools.getIntValue(deals.getProperty(COLOR_TITLE_BARBOTTOM).toString()) + 20);
						}
						university.setDrawable_gradient_separator(Tools.getDrawableSeparator(new int[] { university.getColor_titleBarBottomColor(),
								university.getColor_titleBarTopColor() }));

						if (deals.getProperty(FACEBOOK_URL) != null) {
								university.setFacebookURL( deals.getProperty(FACEBOOK_URL).toString());
						}
						
						if (deals.getProperty(TWITTER_URL) != null) {
							university.setTwitterURL( deals.getProperty(TWITTER_URL).toString());

						}

						// add school to list
						schoolList.add(university);
						
						if (ApplicationEx.getInstance().schoolListMap == null)
							ApplicationEx.getInstance().schoolListMap = new HashMap<String, UniversityDeals>();
						//System.out.println(schoolList.size()+" "+university.getSchoolName());
						ApplicationEx.getInstance().schoolListMap.put(university.getSchoolName(), university);
						
						if (ApplicationEx.getInstance().schoolListString == null){
							ApplicationEx.getInstance().schoolListString = new ArrayList<String>();
						}
						ApplicationEx.getInstance().schoolListString.add((String)university.getSchoolName());
						
					}// end for

				}

			}

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			Intent intent = new Intent(Constant.EVENTS_HTTPCONNECTION_ERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
			// TODO Auto-generated catch block

		} catch (Exception e1) {
			Intent intent = new Intent(Constant.EVENTS_HTTPCONNECTION_ERROR);
			intent.putExtra(Constant.EVENTS_HTTPCONNECTION_MESSAGE, Constant.HTTPCONNECTION_ERROR_MESSAGE);
			ApplicationEx.getInstance().sendBroadcast(intent);
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		if (ApplicationEx.getInstance().schoolListMap != null && (ApplicationEx.getInstance().schoolListMap.size() > 0)) {
			Intent intent = new Intent(Constant.EVENTS_GETSCHOOLLIST);
			ApplicationEx.getInstance().sendBroadcast(intent);
			

			ApplicationEx.getInstance().getSchoolListCompletedStatus = 3;
			

		} else { // no school avail
			Intent intent = new Intent(Constant.EVENTS_GETSCHOOLLIST_ERROR);
			intent.putExtra(Constant.TAG_WEBSERVICE_ERROR_MESSAGE, "No school is available");
			ApplicationEx.getInstance().sendBroadcast(intent);

			ApplicationEx.getInstance().getSchoolListCompletedStatus = 2;

		}

		// return closestUniversity;
	}

}
